//工程管理

/**
 * 添加/编辑工程详情视图模型
 */
interface IProjectManagentDetailViewModelNew {
    /**
     * 需要编辑的工程编号
     */
    id?: string;
    /**
     * 添加/编辑
     */
    title: string;
    /**
     * 工程名称
     */
    projectNameBox: string;
    /**
     * 工程编号
     */
    projectCodeBox: string;
    /**
     * 上限值
     */
    maxValue: number;
    /**
     * 上限值单位
     */
    maxUnit: string;
    /**
     * 收货单位
     */
    settleName?: string;
    /**
     * 收货人
     */
    settleContact?: string;
    /**
     * 收货人联系电话
     */
    settlePhone?: string;
    /**
     * 工程说明
     */
    remarks?: string;
    /**
     * 保存事件
     */
    projectSave: () => void;
}

/**
 * 工程管理视图模型
 */
interface ProjectManagentViewModelNew extends IBaseViewModel<IProjectManagentQueryTermsNew> {
    /**
     * 工程列表组件配置信息
     */
    gridOptions: uiGrid.IGridOptionsOf<ProjectListItemResponse>;
    /**
     *客户单位
     */
    clientName: string;
    /**
     * 工程添加/编辑视图模型
     */
    detail: IProjectManagentDetailViewModelNew;
    /**
     * 添加工程
     */
    projectAdd: () => void;
    /**
     * 编辑工程
     */
    editProject: (id: string) => void;
    /**
     * 删除工程
     */
    delProject: (id: string) => void;
    /**
     * 最大值提示
     */
    maxValueWhole: () => void;

    /**
    * 货物单位下拉
    */
    maxUnitsList: ValueListItemResponse[];
    /**
     * 搜索收货单位(输入时响应)
     */
    searchSettle(value: string):any;
    /**
     * 回调函数
     */
    settleSelect(select:angucomplete<SettleListItemResponse>):void;
    /**
     * 查询
     */
    query:() => void;
    /**
     * 列表高
     */
    // heightA:number;
}

/**
 * 查询条件
 */
interface IProjectManagentQueryTermsNew {
    /**
     * 工程编号
     */
    projectCode: string;
    /**
     * 工程名称
     */
    projectName: string;
}

class ProjectManagentControllerNew extends ListController<ProjectManagentViewModelNew, IProjectManagentQueryTermsNew>{
    gridApi: uiGrid.IGridApiOf<ProjectListItemResponse>;
    enterPriseId: string;

    columnDefs=[
        { name: "序号", field: "index", enableColumnMenu: false,visible:true,cellClass:'list-table-middle list-table-row' },
        {
            name: "操作",
            cellFilter: 'checkmark',
            cellTemplate: '<a data-toggle="modal" title="编辑" data-target="#project" class="primary text-in-table" ng-click="grid.appScope.editProject(row.entity.id)">编辑</a>&nbsp;&nbsp;&nbsp;&nbsp; <a class="primary text-in-table" title="删除" ng-click="grid.appScope.delProject(row.entity.id)">删除</a>', 
            enableColumnMenu: false,
            cellClass:'list-table-middle list-table-row',
            visible:true
        },
        { name: "工程编号", field: "projectCode", enableColumnMenu: false,visible:true },
        { name: "工程名称", field: "projectName", enableColumnMenu: false,visible:true },
        { name: "创建时间", field: "createTime", enableColumnMenu: false ,visible:true },
        { name: "工程总量", field: "maxTon", enableColumnMenu: false,visible:true }
    ]

    constructor(public $scope: ProjectManagentViewModelNew, private projectService: IProjectService, private valueService: valueService,private settleService: ISettleService, private $ngBootbox: BootboxService,private $location:ng.ILocationService,private $timeout:ng.ITimeoutService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();

        this.paginationOptions = {
            skipSize: 0,
            pageSize: 30,
            currentPage: 1
        };

        this.enterPriseId = JSON.parse(window.localStorage.getItem("client").toString()).clientId;
        this.$scope.clientName = JSON.parse(window.localStorage.getItem("client").toString()).clientName;

        this.$scope.projectAdd = this.showAddProjectDialog;
        this.$scope.editProject = this.showEditProjectDialog;
        this.$scope.delProject = this.showDeleteProjectDialog;
        this.$scope.maxValueWhole = this.maxValueWhole;
        this.$scope.searchSettle = this.searchSettle;
        this.$scope.settleSelect = this.settleSelect;



        this.$scope.queryTerms = {
            projectCode: "",
            projectName: ""
        };

        this.$scope.queryTermsFilterList=[
            {name:'工程编号',visible:true},
            {name:'工程名称',visible:true}
        ];

        this.$scope.gridOptions = {
            enableSorting: false,
            // rowHeight:24,
            paginationPageSizes: [ 30, 50, 100,10],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: this.columnDefs,
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.$scope.query = this.query;
        this.query();
        this.loadGoodQuantityUnitDropDown();
    }

    /** 
     * 填充工程总量单位
     */
    loadGoodQuantityUnitDropDown(): void {
        this.$scope.maxUnitsList = this.valueService.getGoodQuantityUnitList().data
    }

    loadData(queryTerms: IProjectManagentQueryTermsNew, skip: number, count: number): void {
        this.projectService.getList(this.enterPriseId, queryTerms.projectCode, queryTerms.projectName, skip, count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            result.data.data.map((item, index) => item.index = skip++ +1);
            this.$scope.gridOptions.data = result.data.data;
            // this.$scope.heightA = (this.$scope.gridOptions.data.length *39)+95;

            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    /**
     * 显示添加工程窗口
     */
    showAddProjectDialog = () => {
        $("#settleContact_value").val("");
        this.$scope.detail = {
            title: "添加工程",
            projectNameBox: "",
            projectCodeBox: "",
            maxValue: null,
            maxUnit: "",
            settleName: "",
            settleContact: "",
            settlePhone: "",
            remarks: "",
            projectSave: this.addProject
        };
    }

    addProject = () => {
        // if (parseInt(this.$scope.detail.maxUnit) > 2 && parseInt(this.$scope.detail.maxUnit) < 7) {
        //     if (!(/(^[0-9]\d*$)/.test(this.$scope.detail.maxValue.toString()))) {
        //         this.$ngBootbox.alert("工程总量请填写正整数");
        //         return;
        //     }
        // }
        if (!$("#projectForm").valid()) { return };
        this.$ngBootbox.confirm("确定保存此数据吗？").then(e => {
            this.projectService.add(
                this.enterPriseId,
                this.$scope.detail.projectNameBox,
                this.$scope.detail.projectCodeBox,
                this.$scope.detail.maxValue,
                this.$scope.detail.maxUnit,
                $("#settleContact_value").val(),
                this.$scope.detail.settleContact,
                this.$scope.detail.settlePhone,
                this.$scope.detail.remarks
            ).then(result => {
                this.reload();
                $("#project").modal("hide");
            })
        });
    }

    /**
     * 显示编辑工程窗口
     */
    showEditProjectDialog = (id: string) => {
        var validator = $('#projectForm').validate();
        validator.form();
        validator.hideErrors();
        $(".error").removeClass("error");
        this.projectService.getDetail(id).then(result => {
            $("#settleContact_value").val(result.data.settleName),
                this.$scope.detail = {
                    title: "编辑工程",
                    id: id,
                    projectNameBox: result.data.projectName,
                    projectCodeBox: result.data.projectCode,
                    maxValue: result.data.maxValue,
                    maxUnit: result.data.maxUnit,
                    settleName: result.data.settleName,
                    settleContact: result.data.settleContact,
                    settlePhone: result.data.settlePhone,
                    remarks: result.data.remarks,
                    projectSave: this.editProject,
                }
        });
    }
    /**
     * 点击保存编辑工程窗口
     */
    editProject = () => {
        // if (parseInt(this.$scope.detail.maxUnit) > 2 && parseInt(this.$scope.detail.maxUnit) < 7) {
        //     if (!(/(^[0-9]\d*$)/.test(this.$scope.detail.maxValue.toString()))) {
        //         this.$ngBootbox.alert("工程总量请填写正整数");
        //         return;
        //     }
        // }
        this.$ngBootbox.confirm("确定保存此数据吗").then(e => {
            this.projectService.edit(
                this.$scope.detail.id,
                this.enterPriseId,
                this.$scope.detail.projectNameBox,
                this.$scope.detail.projectCodeBox,
                this.$scope.detail.maxValue,
                this.$scope.detail.maxUnit,
                $("#settleContact_value").val(),
                this.$scope.detail.settleContact,
                this.$scope.detail.settlePhone,
                this.$scope.detail.remarks
            ).then(result => {
                this.reload();
                $("#project").modal("hide");
            });
        })
    }
    /**
     * 删除工程事件
     */
    showDeleteProjectDialog = (id: string) => {
        this.$ngBootbox.confirm("是否删除该工程？").then(e => {
            this.projectService.delete(id).then(result => {
                this.reload();
            })
        })
    }

    /**
     * 最大值提示
     */
    maxValueWhole = () => {
        if (parseInt(this.$scope.detail.maxUnit) > 2 && parseInt(this.$scope.detail.maxUnit) < 7) {
            if (!(/(^[0-9]\d*$)/.test(this.$scope.detail.toString()))) {
                this.$timeout(()=>{
                    this.$ngBootbox.alert("工程总量请填写正整数");
                }); 
            }
        }
    }

    /**
     * 搜索收货单位(输入时响应)
     */
    searchSettle = (value: string) => {
        return this.settleService.getList(this.enterPriseId, value, "", true, 0, 5).then((res) => {
            return res.data.data;
        }, (rel) => { })
    }
    /**
     * 回调函数
     */
    settleSelect = (select:angucomplete<SettleListItemResponse>) => {
        if (select) {
            this.$scope.detail.settlePhone = select.description.phoneNumber;
            this.$scope.detail.settleContact = select.description.contactMan;
        }
    }

}

angular.module("tms").controller("projectManagentNewController", ["$scope", "projectService", "valueService", "settleService", "$ngBootbox","$location","$timeout", ProjectManagentControllerNew]);